package com.jinke.uang.ui.activity.personal;

import android.content.Intent;
import android.graphics.Paint;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.facebook.accountkit.AccountKitLoginResult;
import com.facebook.accountkit.ui.AccountKitActivity;
import com.facebook.accountkit.ui.AccountKitConfiguration;
import com.facebook.accountkit.ui.LoginType;
import com.facebook.accountkit.ui.ThemeUIManager;
import com.jinke.uang.BuildConfig;
import com.jinke.uang.R;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.bean.LoginData;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.cache.Acache;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.http.ParamsFactory;
import com.jinke.uang.http.RetrofitManager;
import com.jinke.uang.http.Urls;
import com.jinke.uang.main.MainActivity;
import com.jinke.uang.model.LoginModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.rxbus.EventMsg;
import com.jinke.uang.rxbus.Events;
import com.jinke.uang.rxbus.RxBus;
import com.jinke.uang.ui.MainCaActivity;
import com.jinke.uang.utils.StringUtils;
import com.jinke.uang.utils.ToastUtils;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * facebook登录界面
 */
@Route(path = RouterMap.LOGIN_METNOD_PAGE)
public class LoginMethodActivity extends BaseNormalActivity <CommonPresenter, LoginModule>{
    @BindView(R.id.tv_login)
    TextView tvLogin;
    public static int APP_REQUEST_CODE = 99;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }


    @Override
    protected void onUIReady() {
        if (BuildConfig.DEBUG) {
            tvLogin.setVisibility(View.VISIBLE);
            tvLogin.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_login_method;
    }

    @Override
    public String getPageTitle() {
        return null;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected LoginModule getModule() {
        return new LoginModule();
    }

    @OnClick({R.id.tv_login_by_facebook, R.id.tv_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_by_facebook:
                facebook_login();
                break;
            case R.id.tv_login:
                login();
                break;
            default:
                break;
        }
    }

    private void facebook_login() {
        final Intent intent = new Intent(this, AccountKitActivity.class);
        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder = new
                AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
                AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN

        configurationBuilder.setUIManager(new ThemeUIManager(R.style.AppLoginTheme));
        // ... perform additional configuration ...
        intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configurationBuilder.build());
        startActivityForResult(intent, APP_REQUEST_CODE);
    }

    private void login() {
        //判断下是那种登录方式
        Observable<BaseResponse<String>> send =
                RetrofitManager.getInstance().getINetService().loginType(BuildConfig.channel,
                        ParamsFactory.getCommonParams(null));
        send.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(stringBaseResponse -> {
                    if(200==stringBaseResponse.getStatus()){
                       if(stringBaseResponse.getData().equals("1")){
                           facebook_login();
                       }else if(stringBaseResponse.getData().equals("2")){
                           ARouter.getInstance().build(RouterMap.LOGIN_SMS).navigation();
                           finish();
                       }else{
                           ToastUtils.showShort(this,stringBaseResponse.getMessage());
                           ARouter.getInstance().build(RouterMap.LOGIN_PAGE).navigation();
                           finish();
                       }
                    }else{
                        ToastUtils.showShort(this,stringBaseResponse.getMessage());
                        ARouter.getInstance().build(RouterMap.LOGIN_PAGE).navigation();
                        finish();
                    }
                }, throwable -> {
                    ToastUtils.showShort(this,"获取登录方式报错的！");
                    ARouter.getInstance().build(RouterMap.LOGIN_PAGE).navigation();
                    finish();
                });


     /*   ARouter.getInstance().build(RouterMap.LOGIN_PAGE).navigation();
        finish();*/
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == APP_REQUEST_CODE) {
            try {
                AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult
                        .RESULT_KEY);
                String toastMessage;
                if (loginResult.getError() != null) {
                    toastMessage = loginResult.getError().getErrorType().getMessage();
                } else if (loginResult.wasCancelled()) {
                    toastMessage = "Login Cancelled";
                } else {
                    toastMessage = "Success";
                    showLoadingView();
                    mPresenter.getData(HttpConstant.FACEBOOK_LOGIN,null,loginResult.getAuthorizationCode());
                }
                ToastUtils.showShort(this, toastMessage);
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void showResponse(int apiType, String listType,Object o) {
        if(apiType== HttpConstant.FACEBOOK_LOGIN){//facebook登录
            dismissLoadingView();
            BaseResponse<LoginData> loginBaseResponse = (BaseResponse<LoginData>) o;
            String token = loginBaseResponse.getData().getToken();

            if (StringUtils.isEmpty(token)) {
                ToastUtils.showShort(this, getStringResource(R.string.token_is_null));
                return;
            }
            UserInfo.setToken(token);
            ToastUtils.showShort(this, getStringResource(R.string.login_page_login_success));
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(Urls.BASE_URL+"/open.html")
//                    .url("http://47.92.143.84/open.html")
                    .build();
            Call call = okHttpClient.newCall(request);
            //1.异步请求，通过接口回调告知用户 http 的异步执行结果
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    goMainCa();
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        JSONObject jsonObject= JSON.parseObject(response.body().string());
                        if(jsonObject.containsKey("open")&&1==jsonObject.getIntValue("open")){
                            goMain();
                        }else{
                            goMainCa();
                        }
                    }else{
                        goMainCa();
                    }
                }
            });
        }
    }


    private void goMain(){
        Acache.get(getApplication()).put("main","1");
        Intent intent=new Intent(LoginMethodActivity.this, MainActivity.class);
        startActivity(intent);
        //判断下跳转到啥地方
        EventMsg msg = new EventMsg();
        msg.setMsg(Events.LOGIN);
        RxBus.getInstance().post(msg);
        finish();
    }
    private void goMainCa(){
        //判断下跳转到啥地方
       Intent intent=new Intent(LoginMethodActivity.this, MainCaActivity.class);
       startActivity(intent);
        finish();
    }
    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
    }
}
